<?php
/**
 * Created by PhpStorm.
 * User: zhangrxiang
 * Date: 2017/6/29
 * Time: 21:42
 */

//new SQLite3("");

class MyDB extends SQLite3 {
	function __construct() {
		$this->open( 'test.db' );
	}
}

$db = new MyDB();
if ( ! $db ) {
	echo $db->lastErrorMsg();
} else {
	echo "Opened database successfully\n";
}

$sql = <<<SQL
SELECT COUNT(*) FROM sqlite_master where type='table' and name='COMPANY';
SQL;
if ( ! $db->exec( $sql ) ) {
	$sql = <<<EOF
      CREATE TABLE COMPANY
      (ID INT PRIMARY KEY     NOT NULL,
      NAME           TEXT    NOT NULL,
      AGE            INT     NOT NULL,
      ADDRESS        CHAR(50),
      SALARY         REAL);
EOF;
	if ( ! $ret ) {
		echo $db->lastErrorMsg();
	} else {
		echo "Table created successfully\n";
	}
	$ret    = $db->exec( $sql );
	$sql    = <<<SQL
	  INSERT INTO COMPANY (NAME,AGE,ADDRESS,SALARY)
      VALUES ('Paul', 32, 'California', 20000.00 );

      INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
      VALUES ('Allen', 25, 'Texas', 15000.00 );

      INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
      VALUES ('Teddy', 23, 'Norway', 20000.00 );

      INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
      VALUES ('Mark', 25, 'Rich-Mond ', 65000.00 ); 
SQL;
	$result = $db->exec( $sql );
}
//$sql=<<<SQL
//SELECT ID FROM COMPANY ORDER BY ROWID DESC LIMIT 1;
//SQL;
//$lastID = $db->exec($sql);
//echo $lastID;

$lastID = $db->lastInsertRowID();
if ( ! $lastID ) {
	$sql    = <<<SQL
SELECT ID FROM COMPANY ORDER BY ROWID DESC LIMIT 1;
SQL;
	$lastID = $db->querySingle( $sql );
}
echo $lastID;
for ( $i = $lastID + 1; $i < 1000; $i ++ ) {
	$sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
      VALUES (" . $i . ",'Mark1',". $i .",'Rich-Mond', 65000.00 )";
	$db->exec( $sql );
	echo $sql . PHP_EOL;
}
$db->close();
